package com.hxqc.basic.interceptor;

import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.hxqc.basic.common.Constants;
import com.hxqc.basic.serivce.SysUserService;
public class AppServletContextListener implements HttpSessionAttributeListener,ServletContextListener {
	
	
	@SuppressWarnings("unchecked")
	@Override
	public void attributeAdded(HttpSessionBindingEvent sbe) {
		if (sbe.getName().equals(Constants.USER_SESSION_KEY)) {
			
			Map<String,Object> user =(Map<String,Object>)sbe.getValue();
			user.put("session_id", sbe.getSession().getId());
			WebApplicationContext context = WebApplicationContextUtils
					.getWebApplicationContext(sbe.getSession().getServletContext());
			SysUserService sysUserService = context.getBean(SysUserService.class);
			sysUserService.insertLoginLog(user);
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent sbe) {
		if (sbe.getName().equals(Constants.USER_SESSION_KEY)) {	
			WebApplicationContext context = WebApplicationContextUtils
					.getWebApplicationContext(sbe.getSession().getServletContext());
			SysUserService sysUserService = context.getBean(SysUserService.class);
			sysUserService.updateLogoutLogBySessionId(sbe.getSession().getId());
		}
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent hsbe) {
		

	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		WebApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(sce.getServletContext());
		SysUserService sysUserService = context.getBean(SysUserService.class);
		sysUserService.updateLogoutLog();
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		
	}

}